package com.jetpackframework.skin;

import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.jetpackframework.virtual.SkinResource;

import java.util.List;

public class SkinView {
    private final View view;
    private final List<SkinPair> skinPairs;
    private SkinResource resource;

    public SkinView(View view, List<SkinPair> skinPairs) {
        this.view = view;
        this.skinPairs = skinPairs;
        resource = SkinResource.getInstance(view.getContext());
    }

    /**
     * 开始换肤
     */
    public void apply(){
        if (view instanceof SkinViewSupport){
            ((SkinViewSupport) view).apply(view,resource);
            return;
        }
        Drawable left = null,right = null,top = null,bottom = null;
        for (SkinPair pair : skinPairs){
            if (pair.getAttrName().equals(SkinAttributeSets.attrNames[0])){ //背景换肤
                Object backgroud = resource.getBackgroud(pair.getResId());
                if (backgroud instanceof Integer){
                    view.setBackgroundColor((Integer) backgroud);
                }else {
                    view.setBackground((Drawable) backgroud);
                }
            }else if (pair.getAttrName().equals(SkinAttributeSets.attrNames[1])){ //换图片
                Object backgroud = resource.getBackgroud(pair.getResId());
                if (view instanceof ImageView) {
                    if (backgroud instanceof Integer) {
                        ((ImageView) view).setImageDrawable(new ColorDrawable((Integer) backgroud));
                    } else {
                        ((ImageView) view).setImageDrawable((Drawable) backgroud);
                    }
                }
            }else if (pair.getAttrName().equals(SkinAttributeSets.attrNames[2])){  //更换字体颜色
                ((TextView)view).setTextColor(resource.getColorStateList(pair.getResId()));
            }else if (pair.getAttrName().equals(SkinAttributeSets.attrNames[3])){  //drawableLeft属性
                left = resource.getDrawable(pair.getResId());
            }else if (pair.getAttrName().equals(SkinAttributeSets.attrNames[4])){ //drawableTop属性
                top = resource.getDrawable(pair.getResId());
            }else if (pair.getAttrName().equals(SkinAttributeSets.attrNames[5])){ //drawableRight
                right = resource.getDrawable(pair.getResId());
            }else if (pair.getAttrName().equals(SkinAttributeSets.attrNames[6])){ //drawableBottom
                bottom = resource.getDrawable(pair.getResId());
            }
        }
        if ((left != null || right != null || top != null || bottom != null) && view instanceof TextView){
            ((TextView)view).setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom);
        }
    }

}
